package com.caocaog.market.data.transfer.service.impl;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.data.transfer.entity.CcAgentAreaToLead;
import com.caocaog.market.data.transfer.entity.MkSiteArea;
import com.caocaog.market.data.transfer.entity.MkSiteBasic;
import com.caocaog.market.data.transfer.entity.SiteAreaSimple;
import com.caocaog.market.data.transfer.mapper.CcAgentAreaToLeadMapper;
import com.caocaog.market.data.transfer.mapper.MkSiteAreaMapper;
import com.caocaog.market.data.transfer.service.MkSiteAreaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liguang
 * @version 1.0.0
 * @Project jeecg-boot
 * @Package com.caocaog.market.data.transfer.service.impl
 * @ClassName MkSiteAreaServiceImpl.java
 * @createTime 2021年11月16日 10:07:00
 * @Description TODO
 */
@Service
public class MkSiteAreaServiceImpl implements MkSiteAreaService {
    @Autowired
    private CcAgentAreaToLeadMapper ccAgentAreaToLeadMapper;

    @Autowired
    private MkSiteAreaMapper mkSiteAreaMapper;

    @Override
    public IPage<MkSiteArea> findAllSiteAreaByNow(Page<MkSiteArea> page, MkSiteArea mkSiteArea) {
        return mkSiteAreaMapper.findAllSiteAreaByNow(page, mkSiteArea);
    }

    @Override
    public int countForfindAllSiteAreaByNow(MkSiteArea mkSiteArea) {
        return mkSiteAreaMapper.countForfindAllSiteAreaByNow(mkSiteArea);
    }

    @Override
    @CacheEvict(cacheNames = CacheConstant.SYS_ALL_SITE_AREA_CACHE)
    public String insertSiteAreaForInsert(List<MkSiteBasic> siteBasics) {
        String relt = "";
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("agentList------->  " + siteBasics.size());
        for (MkSiteBasic siteBasic : siteBasics) {
            MkSiteArea mkSiteArea = new MkSiteArea();
            mkSiteArea.setSiteId(siteBasic.getId());
            /** 思路：
             *      1、根据迁移过来的分站id，去mk_site_area表中查询迁移过来分站区域；
             *      2、如果没有
             *          2.1 根据分站信息去sqlserver中查询该分站的区域信息
             *          2.2 执行插入；
             *      3、如果有则先删除迁移过来的分站区域再执行插入操作；
             */
            try {
                int siteAreaCount = mkSiteAreaMapper.countForSiteAreaBySiteId(mkSiteArea.getSiteId());
                if (siteAreaCount > 0) {
                    /**
                     * 分站区域已迁移过来，需要重新迁移
                     *      此时：
                     *          先删除mk_site_area表中的迁移过来的分站区域数据
                     *          再  根据sqlserver库中分站的id查询出该分站的区域
                     *          其次   循环插入
                     */
                    // 删除mk_site_area表中迁移过来的分站区域数据
                    Map<String, String> maps = new HashMap<String, String>();
                    maps.put("siteId", siteBasic.getId());
                    int count = mkSiteAreaMapper.deleteSiteAreaBySiteId(maps);
                    if (count > 0) {
                        int co = opertionInsert(siteBasic, mkSiteArea, loginUser);
                        System.out.println("是否执行成功----》   " + co);
                    } else {
                        continue;
                    }
                } else {
                    /**
                     * 分站区域没有迁移过来
                     *      此时：
                     *          根据sqlserver库中分站的id查询出该分站的区域
                     *          循环插入
                     */
                    int co = opertionInsert(siteBasic, mkSiteArea, loginUser);
                    System.out.println("是否执行成功----》   " + co);
                }
            } catch (Exception e) {
                // 出错了  执行失败
                relt = relt + " ”" + siteBasic.getName() + "“ ";
                e.printStackTrace();
                continue;
            }
        }
        return StringUtils.isBlank(relt) ? "分站区域数据迁移执行成功！" : "分站：" + relt + " 区域数据迁移执行失败，请重新执行";
    }

    private int opertionInsert(MkSiteBasic siteBasic, MkSiteArea mkSiteArea, LoginUser loginUser) {
        // 根据sqlserver库中分站的id查询出该分站的区域
        CcAgentAreaToLead ccAgentAreaToLead = new CcAgentAreaToLead();
        ccAgentAreaToLead.setAgentSid(siteBasic.getPtAgentId());
        List<CcAgentAreaToLead> agentAreaList = ccAgentAreaToLeadMapper.findAllSiteAreaByOriginal(ccAgentAreaToLead);
        // 循环插入
        int num = 0;
        for (CcAgentAreaToLead agentArea : agentAreaList) {
            mkSiteArea.setId(String.valueOf(new DefaultIdentifierGenerator().nextId(mkSiteArea)));
            mkSiteArea.setCreateBy(loginUser.getUsername());
            mkSiteArea.setCreateTime(new Date());
            mkSiteArea.setProvinceAdcode(agentArea.getProvinceAdcode());
            mkSiteArea.setProvinceName(agentArea.getProvinceName());
            mkSiteArea.setProvinceCenter(agentArea.getProvinceCenter());
            mkSiteArea.setCityAdcode(agentArea.getCityAdcode());
            mkSiteArea.setCityName(agentArea.getCityName());
            mkSiteArea.setCityCenter(agentArea.getCityCenter());
            mkSiteArea.setDistrictAdcode(agentArea.getDistrictAdcode());
            mkSiteArea.setDistrictName(agentArea.getDistrictName());
            mkSiteArea.setDistrictCenter(agentArea.getDistrictCenter());
            mkSiteArea.setTownAdcode(agentArea.getTownAdcode());
            mkSiteArea.setTownName(agentArea.getTownName());
            mkSiteArea.setTownCenter(agentArea.getTownCenter());
            num = num + mkSiteAreaMapper.insertSiteAreaForInsert(mkSiteArea);
        }
        return num;
    }


    @Override
    @Cacheable(cacheNames = CacheConstant.SYS_ALL_SITE_AREA_CACHE)
    public List<SiteAreaSimple> selectSiteAreaList() {
        Map<String, String> map = new HashMap<>();
        List<MkSiteArea> mkSiteAreas = this.mkSiteAreaMapper.selectSiteAreaList();
        // 根据分站类型（siteType，先暂存于siteArea的siteName中），过滤同分站类型相同的中心点（就是经纬度），减少距离对比次数
        return mkSiteAreas.stream().filter(siteArea -> {
            String center = null;
            switch (siteArea.getSiteName()) {
                case "1": // 省级代理
                    center = siteArea.getProvinceCenter();
                    break;
                case "2": // 市级代理
                    center = siteArea.getCityCenter();
                    break;
                case "3": // 县级代理
                    center = siteArea.getDistrictCenter();
                    break;
                case "4": // 乡镇级代理
                    center = siteArea.getTownCenter();
                    break;
                default:
                    break;
            }
            if (StringUtils.isBlank(center)) {
                return false;
            }
            if (map.containsKey(center)) {
                return false;
            }
            map.put(center, siteArea.getSiteId());
            siteArea.setAreaName(center);
            return true;
        }).map(siteArea -> {
            String[] split = siteArea.getAreaName().split(StringPool.COMMA);
            double siteLat = Double.parseDouble(split[1]);
            double siteLng = Double.parseDouble(split[0]);
            return new SiteAreaSimple(siteArea.getSiteId(), new Double[]{siteLat, siteLng});
        }).collect(Collectors.toList());
    }



    @Override
    public MkSiteArea getSiteAreaByDistrictAdCode(String defSiteCode) {
        List<MkSiteArea> mkSiteAreas = this.mkSiteAreaMapper.getDefaultSite(defSiteCode);
        if (mkSiteAreas.isEmpty()) return null;
        return mkSiteAreas.get(0);
    }


    @Deprecated
    public MkSiteArea getSiteAreaByDistrictAdCodeSource(String districtAdCode) {
        List<MkSiteArea> mkSiteAreas = this.mkSiteAreaMapper.getSiteAreaByDistrictAdCode(districtAdCode);
        if (mkSiteAreas.isEmpty()) return null;
        return mkSiteAreas.get(0);
    }
}
